package io.webfolder.cdp;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;

import io.webfolder.cdp.exception.CdpException;

public class TaskKillProcessManager extends ProcessManager {

	private CdpProcess process;

	public void setProcess(CdpProcess process) {
		this.process = process;
	}

	public boolean kill() {
		Field handleField;
		Object pid;
		if (this.process == null)
			return false;
		try {
			handleField = this.process.getProcess().getClass().getDeclaredField("handle");
		} catch (NoSuchFieldException | SecurityException e) {
			throw new CdpException(e);
		}
		handleField.setAccessible(true);
		try {
			pid = handleField.get(this.process.getProcess());
		} catch (IllegalArgumentException | IllegalAccessException e) {
			throw new CdpException(e);
		}
		try {
			Process process = Runtime.getRuntime()
					.exec(new String[] { "cmd", "/c", "taskkill", "/pid", String.valueOf(pid), "/T", "/F" });
			return (process.waitFor(10L, TimeUnit.SECONDS) && process.exitValue() == 0);
		} catch (IOException | InterruptedException e) {
			throw new CdpException(e);
		}
	}
}